package com.cn.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Component
public class RedisUtils {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private Map<String,ResourceScriptSource> scriptSource = new HashMap<>();

    @PostConstruct
    public void init(){
        setScript("deduction");
    }

    public ResourceScriptSource getScriptSource(String key){
        ResourceScriptSource script = null;
        setScript(key);
        script = scriptSource.get(key);
        return script;
    }

    private void setScript(String key){
        if(!scriptSource.containsKey(key)){
            scriptSource.put(key,new ResourceScriptSource(new ClassPathResource("redis/"+key+".lua")));
        }
    }

    public Long deduction(String key,Long val){
        Long result = 0L;
        try {
            //调用lua脚本并执行
            DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
            redisScript.setResultType(Long.class);//返回类型是Long
            //lua文件存放在resources目录下的redis文件夹内
            ResourceScriptSource script = getScriptSource("deduction");
            redisScript.setScriptSource(script);
            result = (Long) redisTemplate.execute(redisScript, Arrays.asList(key), val);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
